<?php

namespace App\Models;

use App\Models\Activity\FlashSale;
use App\Models\Activity\GroupProduct;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use SoftDeletes;

    protected $appends = ['img','activity','merchant_type'];

    public function getImgAttribute(){
        $img =  ProductImage::where('product_id',$this->id)->where('type',1)->first();
        if ($img){
            return  $img->url;
        }
        return null;
    }
    public function getActivityAttribute(){
        switch ($this->activity_type){
            case 1:{
                return null;
            }break;
            case 2:{
                return GroupProduct::where('product_id',$this->id)->first();
            }break;
            case 3:{
                return FlashSale::where('product_id',$this->id)->first();
            }break;
        }
    }
    public function getMerchantTypeAttribute(){
        return Merchant::findOrFail($this->merchant_id)->type;
    }
    public function getDetailAttribute($value){
        if (empty($value)) {
            return '';
        } else {
            return $value;
        }
    }

    public function orders(){
        return $this->belongsToMany('App\Models\Order','order_products','product_id','order_id')
            ->withPivot('product_name','image_id','current_price','activity_type','activity_id','quantity','total_price')
            ->withTimestamps();
    }

    public function users(){
        return $this->belongsToMany('App\Models\SUsers','order_products','product_id','user_id')
            ->withPivot('product_name','image_id','current_price','activity_type','activity_id','quantity','total_price')
            ->orderBy('created_at','desc')
            ->withTimestamps();
    }



}
